import time

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from pywinauto import Desktop


class ChormeOprate:
    def __init__(self):
        # 初始化设置
        options = webdriver.ChromeOptions()
        options.add_experimental_option("detach", True)
        # 启动浏览器，并将options加到浏览器对象里可以保证浏览器不会自动关闭
        self.driver = webdriver.Chrome(options=options)

    # 查找元素
    def find_element(self, locator):
        return self.driver.find_element(*locator)

    # 点击
    def click_element(self, locator):
        el = self.find_element(locator)
        el.click()

    # 右击
    def right_click_element(self, locator):
        el = self.find_element(locator)
        ActionChains(self.driver).context_click(el).perform()

    # 双击
    def double_click_element(self, locator):
        el = self.find_element(locator)
        ActionChains(self.driver).double_click(el).perform()

    # 强制点击
    def click_element_by_force(self, locator):
        el = self.driver.find_element(locator)
        action = ActionChains(self.driver)
        action.move_to_element(el).click().perform()

    # 显性等待
    def wait_for_element(self, locator, timeout=60):
        WebDriverWait(self.driver, timeout=timeout).until(expected_conditions.presence_of_element_located(locator))

    # 上传文件
    def upload_file(self, locator, filepath):
        self.click_element(locator)
        app = Desktop()
        dialog = app["打开"]
        dialog["Edit"].type_keys(filepath)
        time.sleep(5)
        dialog["打开"].click()

    # 输入文本
    def input_text(self, locator, text='null'):
        el = self.find_element(locator)
        el.send_keys(text)

    # 悬停
    def move_to_element(self, locator):
        el = self.find_element(locator)
        ActionChains(self.driver).move_to_element(el).perform()

    # 拖动
    def drag(self, locator1, locator2):
        el1 = self.find_element(locator1)
        el2 = self.find_element(locator2)
        ActionChains(self.driver).drag_and_drop(el1, el2).perform()

    # 切换到frame子页面
    def switch_to_frame(self, locator):
        el = self.find_element(locator)
        self.driver.switch_to.frame(el)

    # 切换回主页面
    def back_to_default_page(self):
        self.driver.switch_to.default_content()

    # 窗口滚动,默认到底部
    def slide_window(self, x=0, y="document.body.srcollHeight"):
        self.driver.execute_script(f"window.scrollTo({x},{y})")

    # 滑动到可视范围
    def element_visible(self, locator):
        el = self.find_element(locator)
        el.location_once_scrolled_into_view
